﻿using DFGJ.WMS_PDA.WebAPI.CfgFile;
using DFGJ.WMS_PDA.WebAPI.Extensions;
using DFGJ.WMS_PDA.WebAPI.Utility.Filters;
using DFGK.WMS.Common.Result;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Formula.PTG;
using SqlSugar;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;

namespace DFGJ.WMS_PDA.WebAPI.Controllers.PDA
{
    /// <summary>
    /// PDA接口 
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [AllowAnonymous]
    public class PDAHandlerController : ControllerBase
    {

        #region Service 
        private readonly ILogger<PDAHandlerController> _Logger;

        private readonly DFGK_DB _dbContext;

        private readonly ISqlSugarClient _Client;

        //入库单明细 
        private readonly ITReceivingOrderDetailRepository _TRecevingDetail;

        //收货单
        private readonly ITReceivingBillRepository _TReceivingBill;

        //站台
        private readonly ITStationRepository _TStation;

        //入库垛  
        private readonly IStackingStorageRepository _StackingStorage;

        //倒垛
        private readonly IStackingStorageService _IStackStorageService;
        private readonly ILogRepository logRepository;

        #endregion



        public PDAHandlerController
            (ILogger<PDAHandlerController> logger,
             DFGK_DB dbContext,
             ITReceivingOrderDetailRepository orderDetailRepository,
             ITReceivingBillRepository tReceivingBill,
             ITStationRepository tStation,
             ISqlSugarClient client,
             IStackingStorageRepository stackingStorage,
             IStackingStorageService iStackStorageService,
             ILogRepository logRepository
           )

        {
            _Logger = logger;
            _dbContext = dbContext;
            _TRecevingDetail = orderDetailRepository;
            _TReceivingBill = tReceivingBill;
            _TStation = tStation;
            _Client = client;
            _StackingStorage = stackingStorage;
            _IStackStorageService = iStackStorageService;
            this.logRepository = logRepository;
        }

        /// <summary>
        /// 逻辑分区
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetDictItems")]
        public IActionResult GetDictItems()
        {
            try
            {
                var list = _TReceivingBill.GetDictItems();
                if (list != null && list.Count != 0)
                {
                    return Ok(BaseResult.Result(list, "查询成功", "500"));
                }
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }
            catch (Exception ex)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }
        }


        #region 获取入库单明细数据
        /// <summary>
        /// 获取入库单明细数据
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="wareHouseId">库房Id</param>
        /// <param name="searchaString">关键字</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrderListAsync/{pageIndex}/{pageSize}")]
        public async Task<IActionResult> GetOrderListAsync(int pageIndex, int pageSize, int? wareHouseId, string? searchaString = null)
        {
            try
            {

                ISugarQueryable<TReceivingOrderDetail> iQueryable = _Client.Queryable<TReceivingOrderDetail>().Where(it => it.Status >= 1 && it.Status < 4);

                iQueryable = iQueryable.WhereIF(wareHouseId != null, it => it.WarehouseId == wareHouseId);

                if (!string.IsNullOrWhiteSpace(searchaString))
                {
                    iQueryable = iQueryable.Where(t => t.OrderSn == searchaString || t.BatchNo == searchaString || t.OwnerName.Contains(searchaString) || t.MaterialCode == searchaString);
                }
                int totalCount = iQueryable.Count();
                PagingData<TReceivingOrderDetail> pagingData = new PagingData<TReceivingOrderDetail>()
                {
                    DataList = iQueryable.OrderBy(it => it.Id).ToPageList(pageIndex, pageSize),
                    RecordCount = totalCount
                };

                ApiResult<PagingData<TReceivingOrderDetail>> apiResult = new ApiResult<PagingData<TReceivingOrderDetail>>()
                {
                    Data = pagingData,
                    Success = true,
                    Code = "200"
                };
                return await Task.FromResult(new JsonResult(apiResult));

            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = ex.Message }));

            }


        }

        /// <summary>
        /// 根据订单号查询入库单
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceiving")]
        public IActionResult GetReceiving(string OrderSn)
        {
            if (OrderSn is null)
            {
                return Ok(BaseResult.Result(null, "订单号不能为空", "500"));
            }
            var receivingOrder = _Client.Queryable<TReceivingOrderDetail>().Where(r => r.OrderSn == OrderSn && r.Status == 3).ToList();
            if (receivingOrder.Count > 0)
            {
                return Ok(BaseResult.Result(new
                {
                    count = receivingOrder.Count,
                    nowcount = receivingOrder.Where(r => r.Status == 4).Count() + 1,
                    data = receivingOrder.FirstOrDefault()

                }, "", "200"));
            }

            return Ok(BaseResult.Result(null, "订单已经没有数据了", "200"));
        }


        #endregion

        #region 提交入库单执行
        /// <summary>
        /// 执行入库作业
        /// </summary>
        /// <param name="orderDetailDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitOrder")]
        [TypeFilter(typeof(IdempotentFilterAttribute))]
        public async Task<IActionResult> SubmitOrder(ReceivingOrderDetailDto orderDetailDto)
        {
            try
            {
                bool result = false;
                TReceivingOrderDetail orderDetail = _Client.Queryable<TReceivingOrderDetail>().Single(it => it.Id == orderDetailDto.Id);
                if (orderDetail == null)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到订单：" + orderDetailDto.Id }));
                }

                List<TStation> inAndOutPortStations = _Client.Queryable<TStation>().Where(it => it.StationType == 1 && it.WhId == orderDetail.WarehouseId).ToList();
                if (inAndOutPortStations == null || inAndOutPortStations.Count == 0)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到可用的出入口站台" }));

                }
                //调用外部接口
                result = true;
                if (!result)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "调用外部服务失败" }));
                }

                string errMsg;
                result = _TRecevingDetail.ExecReceving(orderDetail, out errMsg);

                ApiBaseResult baseResult = new ApiBaseResult()
                {
                    Success = true,
                    Message = "入库执行成功"
                };
                if (!result)
                {
                    baseResult = new ApiBaseResult()
                    {
                        Success = false,
                        Message = errMsg
                    };
                }

                return await Task.FromResult(new JsonResult(baseResult));
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = ex.Message })); throw;
            }



        }

        #endregion


        #region 收货、组垛、入库  

        /*1、获取收货单 */
        /// <summary>
        /// 获取收货单明细数据
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="warehouseid">仓库</param>
        /// <param name="searchaString"></param>
        [HttpGet]
        [Route("GettReceivingBillList/{pageIndex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetReceivingBillList(int pageIndex, int pageSize, int? warehouseid)
        {
            try
            {
                //Expressionable<TReceivingBill> where = Expressionable.Create<TReceivingBill>();
                //where.And(c => c.Status < 2);
                //where.And(c => c.WarehouseId == warehouseid);

                Expression<Func<TReceivingBill, bool>> where = t => t.Status < 2 && t.WarehouseId == warehouseid;

                List<int?> billIds = _dbContext.Set<TReceivingBill>()
                    .Where(where)
                    .Select(it => it.WarehouseId)
                    .ToList();
                if (billIds == null || billIds.Count == 0)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "暂无收货单" }));
                }
                IQueryable<TReceivingBillDetail> billDetailsQuery = _dbContext.Set<TReceivingBillDetail>()
                    .Where(it => billIds.Contains(it.BillId) && it.Status < 2)
                    .Where(it => it.Qty != it.ReceivedQty)
                    .AsQueryable();

                int count = billDetailsQuery.Count();
                List<TReceivingBillDetail> billDetails = billDetailsQuery
                     .Skip(pageIndex)
                     .Take(pageSize)
                     .OrderBy(it => it.Id)
                     .ToList();

                PagingData<TReceivingBillDetail> pagingData = new PagingData<TReceivingBillDetail>()
                {
                    DataList = billDetails,
                    RecordCount = count
                };

                ApiResult<PagingData<TReceivingBillDetail>> apiResult = new ApiResult<PagingData<TReceivingBillDetail>>()
                {
                    Code = "200",
                    Data = pagingData,
                    Success = true

                };


                return await Task.FromResult(new JsonResult(apiResult));
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                throw new Exception(ex.Message);

            }

        }

        /*2、生成入库单  一个物料生成一个入库单*/
        /// <summary>
        /// 创建入库单
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateReceivingOrder")]
        [ValidateParaFilter]

        public async Task<IActionResult> CreateReceivingOrder(ReceivingOrderDto orderDto)
        {
            try
            {
                #region 参数校验
                //获取站台信息
                bool inAndOutPortStations = await _dbContext.TStations.AnyAsync(it => it.StationType == 1);
                if (!inAndOutPortStations)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到可用的出入口站台" }));
                }

                //获取收货单详情
                var receivingBillBillDetail = _TRecevingDetail.GetTReceivingOrderDetailById(orderDto.RecevingBillDetailId);
                if (receivingBillBillDetail is null)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "收货单不存在" }));

                }
                //判断收获数量填写是否正确
                if ((receivingBillBillDetail.Qty - receivingBillBillDetail.ReceivedQty - orderDto.Qty) < 0)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "收货数量填写有误" }));
                }
                #endregion

                #region 添加入库单详情

                string errMsg;
                bool result = _TRecevingDetail.AddTReceivingOrderDetail(orderDto.RecevingBillDetailId, orderDto.Qty, out errMsg);
                if (result)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = true, Message = "添加成功" }));
                }
                else
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = errMsg }));

                }
                #endregion

            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                throw new Exception(ex.Message);
            }

        }


        /*3、PDA组垛*/
        /// <summary>
        /// PDA组垛
        /// </summary>
        /// <param name="palletBind"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateStackingStorage")]
        public async Task<JsonResult> CreateStackingStorage(PalletBindMaterialDto palletBind)
        {
            try
            {
                string errMsg;

                bool result = _StackingStorage.CreateStackingStorage(palletBind, out errMsg);
                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = result,
                    Message = errMsg
                };
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = false,
                    Message = "程序异常：" + ex.Message
                };
                return new JsonResult(apiResult);

            }


            return null;
        }
        #endregion

        #region  入库解绑
        /// <summary>
        /// 弃用
        /// </summary>
        /// <param name="unbindData">托盘条码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitUnbindOfInstorage")]
        [ValidateParaFilter]

        public IActionResult SubmitUnbindOfInstorage(UnbindInstorageDto unbindData)
        {
            try
            {
                string msg;
                bool result = _StackingStorage.HandleUnbindOfInstorage(unbindData.PalletBarcode, out msg);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = result,
                    Message = msg
                };
                return new JsonResult(apiResult);
            }
            catch (Exception ex)
            {

                _Logger.LogError(ex.Message);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = false,
                    Message = "程序异常:" + ex.Message
                };
                return new JsonResult(apiResult);



            }

        }

        #endregion


        /// <summary>
        /// 消防支队PDA组垛理货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitPalletTallyPDAData")]
        [TypeFilter(typeof(LogActionFilter))]
        public IActionResult SubmitPalletTallyPDAData(PalletTallyInputModel data)
        {
            try
            {
                if (data.OrderDetailId.GetValueOrDefault() <= 0 || string.IsNullOrEmpty(data.PalletBarcode) || data.PalletPackage == null)
                {
                    return new JsonResult(new ApiBaseResult { Code = "201", Success = false, Message = "参数错误" });
                }

                string errMsg = string.Empty;
                bool result = _IStackStorageService.BuildCreateStackingStorage(out errMsg, data);

                ApiBaseResult baseResult = new ApiBaseResult();
                if (!result)
                {
                    baseResult.Code = "500";
                    baseResult.Success = false;
                    baseResult.Message = errMsg;
                    return Ok(baseResult);
                }
                //result = _IStackStorageService.ExecCreateInstruct(out errMsg,);
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message = "操作成功";
                return new JsonResult(baseResult);

            }
            catch (Exception)
            {

                throw;
            }


        }


        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="startInventoryDTO"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExecCreateInventory")]
        [TypeFilter(typeof(LogActionFilter))]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult ExecCreateInventory(StartInventoryDTO startInventoryDTO)
        {
            ApiBaseResult baseResult = new ApiBaseResult();
            if (string.IsNullOrEmpty(startInventoryDTO.PalletCode) || string.IsNullOrEmpty(startInventoryDTO.ActualLocation))
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "参数有误";
                return Ok(baseResult);
            }

            var stackingStoragelist = _Client.Queryable<TStackingStorage>().Where(s => s.Status == 1 && s.PalletBarcode == startInventoryDTO.PalletCode).ToList();
            if (stackingStoragelist is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "无组垛信息";
                return Ok(baseResult);
            }

            var cell = _Client.Queryable<TCell>().First(c => c.Code == startInventoryDTO.ActualLocation);
            if (cell is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "仓位不存在" + startInventoryDTO.ActualLocation;
                return Ok(baseResult);
            }
            //最优站台
            startInventoryDTO.StationCode = GetStockCode(startInventoryDTO.ActualLocation);
            if (stackingStoragelist.First().ExpectedLocation != startInventoryDTO.ActualLocation)
            {
                if (cell.FullStatus == 1 || cell.Status == 2 || cell.IsLock == true)
                {
                    baseResult.Code = "500";
                    baseResult.Success = false;
                    baseResult.Message = "仓位已被占用" + startInventoryDTO.ActualLocation;
                    return Ok(baseResult);
                }
            }
            string errMsg = "";
            bool result = false;
            try
            {
                var orderDetail = _Client.Queryable<TReceivingOrderDetail>().First(x => x.Id == stackingStoragelist.First().RelatedOrderDetailId);
                TStation station = _Client.Queryable<TStation>().First(r => r.WhId == orderDetail.WarehouseId);
                errMsg = string.Empty;
                result = _IStackStorageService.ExecCreateInstruct(out errMsg, orderDetail, station, startInventoryDTO.ActualLocation, stackingStoragelist, startInventoryDTO.StationCode);
                if (!result)
                {
                    return Ok(BaseResult.Result("500", errMsg));
                }
            }
            catch (Exception)
            {
                return Ok(BaseResult.Result("500", errMsg));
            }
            string uname = HttpContext.User.FindFirstValue("UserName");
            string runame = HttpContext.User.FindFirstValue("RealName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
            TLog logg = new TLog();
            logg.LogType = 1;
            logg.ActionType = 4;
            logg.ModuleName = "添加入库";
            logg.UserName = uname;
            logg.RealName = runame;
            logg.UserId = uid;
            logg.Description = result ? uname + "入库成功" : uname + "入库失败: " + errMsg;
            logg.Ipaddress = ip;
            logRepository.AddTLod(logg);
            if (!result)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = errMsg;
                return Ok(baseResult);
            }
            baseResult.Code = "200";
            baseResult.Success = true;
            baseResult.Message = "操作成功";
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 入库最优站台编码
        /// </summary>
        /// <param name="ActualLocation"></param>
        /// <returns></returns>
        private string GetStockCode(string ActualLocation)
        {
            int a, b;
            string code = "";
            MatchCollection match = Regex.Matches(ActualLocation, @"\d");
            if (match.Count >= 2)
            {
                a = Convert.ToInt32(match[0].Value);
                b = Convert.ToInt32(match[1].Value);
                if (a == 1 && (a + b == 2 || a + b == 3 || a + b == 4 || a + b == 5))
                {
                    code = "1700";
                }
                else if (a == 2 && (a + b == 3 || a + b == 4 || a + b == 5 || a + b == 6))
                {
                    code = "1500";
                }
                else if (a == 3 && (a + b == 4 || a + b == 5 || a + b == 6 || a + b == 7))
                {
                    code = "1300";
                }
                else
                {
                    code = "1100";
                }
            }

            return code;
        }

        /// <summary>
        /// 查询入库单
        /// </summary>
        /// <param name="PalletCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBill")]
        public IActionResult GetReceivingBill(string PalletCode)
        {
            var stackingStoragelist = _Client.Queryable<TStackingStorage>().Where(s => s.Status == 1 && s.PalletBarcode == PalletCode).ToList();

            if (!stackingStoragelist.Any())
            {
                return Ok(BaseResult.Result(null, "无组垛信息", "500"));
            }
            var invobj = _Client.Queryable<TInventory>().Where(x => x.PalletBarcode == PalletCode).ToList();
            if (invobj.Any() || (invobj.Any() && invobj.First().IsLock == true))
            {
                return Ok(BaseResult.Result(null, "该托盘正在作业中", "500"));
            }
            var orderDetail = _Client.Queryable<TReceivingOrderDetail>().ToList();
            if (orderDetail is null)
            {
                return Ok(BaseResult.Result(null, "入库单查询失败", "500"));
            }
            StackingReceivingsDto srmodel = new StackingReceivingsDto();
            string cellcode = "";
            foreach (var item in stackingStoragelist)
            {
                var orderDetailobj = orderDetail.FirstOrDefault(x => x.Id == item.RelatedOrderDetailId && x.Status == 3);
                if (orderDetailobj != null)
                {
                    srmodel.PallteCode = PalletCode;
                    srmodel.Cell = item.ExpectedLocation;
                    cellcode = item.ExpectedLocation;
                    srmodel.OrderNo = orderDetailobj.OrderSn;
                    MaterNum maternum = new MaterNum();
                    maternum.MaterialCode = item.MaterialCode;
                    maternum.Num = orderDetailobj.StackedQty;
                    srmodel.materNum.Add(maternum);
                }
            }
            MatchCollection match = Regex.Matches(cellcode, @"\d");
            if (Convert.ToInt32(match[0].Value)==4)
            {
                var putobj = _Client.Queryable<TPutawayOrder>().Where(x => x.SourceType == 2 && x.Status == 1 && x.LocationCode.Contains("4巷道"));
                if(putobj.Any())
                {
                    return Ok(BaseResult.Result(null, "有出库任务在执行", "500"));
                }
            }         

            return Ok(BaseResult.Result(srmodel, "成功", "200"));
        }

        /// <summary>
        /// 判断托盘是否可用
        /// </summary>
        /// <param name="PalletCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("PalletVerify")]
        public IActionResult PalletVerify(string PalletCode)
        {
            var pallet = _Client.Queryable<TPallet>().First(p => p.PalletBarcode == PalletCode);
            ApiBaseResult baseResult = new ApiBaseResult();
            if (pallet is null)
            {
                baseResult.Code = "200";
                baseResult.Success = false;
                baseResult.Message = "托盘不存在";
                return Ok(baseResult);
            }
            //var storageModellist = _Client.Queryable<TStackingStorage>().Where(r => r.Status == 1 && r.PalletBarcode == PalletCode).ToList();
            //if (storageModellist != null && storageModellist.Count() > 3)
            //{
            //    baseResult.Code = "200";
            //    baseResult.Success = false;
            //    baseResult.Message = "托盘超出组垛数量";
            //    return Ok(baseResult);
            //}
            var inventory = _Client.Queryable<TInventory>().First(r => r.PalletBarcode == PalletCode);
            if (inventory is not null)
            {
                baseResult.Code = "200";
                baseResult.Success = false;
                baseResult.Message = "当前托盘已在库存中";
                return Ok(baseResult);
            }

            baseResult.Code = "200";
            baseResult.Success = true;
            baseResult.Message = "";
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 判断小批号是否存在
        /// </summary>
        /// <param name="SmallBatchNo"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetlittleBatchNo")]
        public IActionResult GetlittleBatchNo(string SmallBatchNo)
        {
            var recevingorder = _Client.Queryable<TReceivingOrderDetail>().First(r => r.SmallBatchNo == SmallBatchNo);
            ApiBaseResult baseResult = new ApiBaseResult();
            if (recevingorder is not null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "有相同的小批次号";
                return Ok(baseResult);
            }
            baseResult.Code = "200";
            baseResult.Success = true;
            baseResult.Message = "";
            return new JsonResult(baseResult);
        }

        [HttpGet]
        [Route("getbatchno")]
        public IActionResult getbatchno(string batchno)
        {
            // string pattern = @"([a-zA-Z0-9]+)([a-z])([a-z-]*)";
            // Regex regex = new Regex(pattern);

            // string result = regex.Replace(batchno, m =>
            // {
            //     string group1 = m.Groups[1].Value;
            //     string group2 = m.Groups[2].Value.ToUpper();
            //     string group3 = m.Groups[3].Value;

            //     return group1 + group2 + group3;
            // });

            //string a = Regex.Replace(batchno, "(^|-)([a-z])", match => match.Groups[1].Value + match.Groups[2].Value.ToUpperInvariant());
            string pattern = @"([A-Za-z])([a-z])-([a-z])";
            string replacement = "$1$2-$2";
            string output = Regex.Replace(batchno, pattern, replacement);
            return Ok(output);
        }

        /// <summary>
        /// 查询全部收货单(分页)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="supplierId"></param>
        /// <param name="status"></param>
        /// <param name="warehouseId"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBillList")]
        public IActionResult GetReceivingBillList(string? key, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = _TReceivingBill.GetReceivingBillList(key, pageIndex, pageSize, out totalCount).ToList();
            if (list.Count <= 0)
            {
                return Ok(BaseResult.Result(list, "目前没有收货单！", "200", totalCount));
            }
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 查询收货单的商品
        /// </summary>
        /// <param name="receivingBillId"></param>
        /// <param name="materialCodeArticlebarcode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBillGoodsDeatil")]
        public IActionResult GetReceivingBillGoodsDeatil(int receivingBillId, string? materialCodeArticlebarcode)
        {
            ApiBaseResult baseResult = new ApiBaseResult();
            if (receivingBillId <= 0 || materialCodeArticlebarcode is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "参数有误";
                return Ok(baseResult);
            }

            //var material = _Client.Queryable<TMaterial>().First(m => m.Articlebarcode == materialCodeArticlebarcode);

            //if (material is not null)
            //{
            //    materialCodeArticlebarcode = material.Code;
            //}
            //else
            //{
            //    material = _Client.Queryable<TMaterial>().First(m => m.Code == materialCodeArticlebarcode);
            //    if (material is null)
            //    {
            //        baseResult.Code = "500";
            //        baseResult.Success = false;
            //        baseResult.Message = "未查出物料";
            //        return Ok(baseResult);
            //    }
            //    materialCodeArticlebarcode = material.Code;
            //}
            var recevingbilldeta = _Client.Queryable<TReceivingBillDetail>().First(r => r.BillId == receivingBillId && r.MaterialCode == materialCodeArticlebarcode);

            if (recevingbilldeta is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "未查出物料";
                return Ok(baseResult);
            }
            return Ok(BaseResult.Result(recevingbilldeta, "查询成功", "200"));
        }



        /// <summary>
        /// PDA收货入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("BuildCreateStackingStorage")]
        [TypeFilter(typeof(LogActionFilter))]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult BuildCreateStackingStorage(ReceivingBillOrderDto m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            string message = "";
            m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");
            List<TCell> Getcell = new List<TCell>();
            bool IsOK = _TReceivingBill.AddPDAReceivingOrderDateil(m, out message, ref Getcell);
            string uname = HttpContext.User.FindFirstValue("UserName");
            string runame = HttpContext.User.FindFirstValue("RealName");
            int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserRealName = uname;//创建人
            m.NowUserId = uid;//创建人id
            string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
            TLog logg = new TLog();
            logg.LogType = 1;
            logg.ActionType = 4;
            logg.ModuleName = "添加组垛";
            logg.UserName = uname;
            logg.RealName = runame;
            logg.UserId = uid;
            logg.Description = IsOK ? uname + "创建了组垛" : uname + "创建组垛失败: " + message;
            logg.Ipaddress = ip;
            logRepository.AddTLod(logg);
            if (IsOK)
            {
                var iscell = "";
                foreach (var item in Getcell)
                {
                    iscell += item.Code;
                }
                return Ok(BaseResult.Result(true, "保存成功！分配的仓位为：" + iscell, "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// 获取小批次号
        /// </summary>
        /// <param name="BatchNo"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetSmallBatchNo")]
        public IActionResult GetSmallBatchNo(string BatchNo)
        {
            if (BatchNo is null || BatchNo == "")
            {
                return Ok(BaseResult.Result("500", "参数有误！"));
            }
            string res = "";
            var data = BatchNo.ToArray();
            if (GetMM(data[4]) == "")
            {
                return Ok(BaseResult.Result("500", "没有查出相对应的月份！"));
            }
            res = res + data[0].ToString();
            res = res + "20" + data[2].ToString() + data[3].ToString();
            res = res + GetMM(data[4]);
            res = res + data[5].ToString() + data[6].ToString();
            res = res + data[1].ToString();
            res = res + data[7].ToString() + data[8].ToString() + data[9].ToString();
            return Ok(BaseResult.Result(res, "成功生成小批次号！", "200"));

        }
        private string GetMM(char zm)
        {
            switch (zm)
            {
                case 'A':
                    return "00";
                case 'B':
                    return "01";
                case 'C':
                    return "02";
                case 'D':
                    return "03";
                case 'E':
                    return "04";
                case 'F':
                    return "05";
                case 'G':
                    return "06";
                case 'H':
                    return "07";
                case 'J':
                    return "08";
                case 'K':
                    return "09";
                case 'L':
                    return "10";
                case 'M':
                    return "11";
                case 'N':
                    return "12";
                case 'O':
                    return "13";
                case 'P':
                    return "14";
                case 'Q':
                    return "15";
                case 'R':
                    return "16";
                case 'S':
                    return "17";
                case 'T':
                    return "18";
                case 'U':
                    return "19";
                case 'V':
                    return "20";
                case 'W':
                    return "21";
                case 'X':
                    return "22";
                case 'Y':
                    return "23";
                case 'Z':
                    return "24";
                default:
                    return "";
            }
        }
    }
}
